package cn.edu.zufe.mjt.binary;

import cn.edu.zufe.mjt.validator.Validator;

import java.util.*;

/**
 * 二分问题，查找是否存在某个数
 */
public class FindX {
    public static void main(String[] args) {
        int[] ints = Validator.randomArray(10, 100);
        // 把 ints 转为 map
        Arrays.sort(ints);
        System.out.println(Arrays.toString(ints));
        int i = (int) (Math.random() * 100);
        int x = findX(ints, i);
        System.out.println(x);
    }

    public static int findX(int[] arr, int x) {
        int left = 0;
        int right = arr.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (arr[mid] == x) {
                return mid;
            } else if (arr[mid] < x) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return -1;
    }
}
